package rest

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"monoblog/common"
	"monoblog/domain/dto"
	"monoblog/domain/service"
)

/*
分类接口
*/

func CategoryAdd(ctx *gin.Context) {
	var form dto.CategoryReqForm
	if err := ctx.ShouldBind(&form); err != nil {
		common.Fail(ctx, "Body数据绑定失败", err)
		return
	}
	//初始化校验器并执行字段校验
	validate := validator.New()
	if err := validate.Struct(form); err != nil {
		common.Fail(ctx, "参数校验失败", err)
		return
	}

	id, err := service.GetCategoryService().Add(ctx, form)
	if err != nil {
		common.Fail(ctx, "添加分类失败", err)
		return
	}
	common.Success(ctx, id)
}

func CategoryUpdate(ctx *gin.Context) {
	id := ctx.Param("id")

	var form dto.CategoryReqForm
	if err := ctx.ShouldBind(&form); err != nil {
		common.Fail(ctx, "Body数据绑定失败", err)
		return
	}

	//初始化校验器并执行字段校验
	validate := validator.New()
	if err := validate.Struct(form); err != nil {
		common.Fail(ctx, "参数校验失败", err)
		return
	}

	err := service.GetCategoryService().UpdateByID(ctx, id, form)
	if err != nil {
		common.Fail(ctx, "更新分类失败", err)
		return
	}
	common.Success(ctx, nil)
}

func CategoryDelete(ctx *gin.Context) {
	id := ctx.Param("id")
	err := service.GetCategoryService().DeleteByID(ctx, id)
	if err != nil {
		common.Fail(ctx, "删除分类失败", err)
		return
	}
	common.Success(ctx, nil)
}

func CategoryFindList(ctx *gin.Context) {
	categories, err := service.GetCategoryService().FindList(ctx)
	if err != nil {
		common.Fail(ctx, "查询分类列表失败", err)
		return
	}
	common.Success(ctx, categories)
}
